/*
 * ===================================================
 *
 *       Filename:  error.c
 *
 *
 *        Created:  10/21/2011 12:58:32 AM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  durand_y, <durand.yoan@gmail.com>
 *
 * ===================================================
 */
#include "parser.h"

static char     *my_itoa(int nb)
{
  char          *str = NULL;
  char          c = '0';
  int           i = 0;
  char          tmp = ' ';

  str = malloc(sizeof(char));
  if (nb < 10)
    str[0] = nb + c;
  else
  {
    while(nb > 10)
    {
      str[i] = (nb % 10) + c;
      i++;
      nb = nb /10;
    }
    str[i] = nb + c;

    for (i = 0; i < (mystrlen(str) / 2); i++)
    {
      tmp = str[i];
      str[i] = str[mystrlen(str) - i - 1];
      str[mystrlen(str) - i - 1] = tmp;
    }
  }

  return (str);
}

void    error(int   err,
              int   pos1,
              int   pos2)
{
  char  *parse = "CarSimulator: invalid sequence at  character: ";
  char  *map = "CarSimulator: map error\n";
  char  *crash = "CarSimulator: car crashed at position: ";

  if (err == 1)
  {
    parse = mystrcat(parse, my_itoa(pos1));
    parse = mystrcat(parse, "\n");
    write(STDERR_FILENO, parse, mystrlen(parse));
  }

  if (err == 3)
    write(STDOUT_FILENO, map, mystrlen(map));

  if (err == 2)
  {
    crash = mystrcat(crash, my_itoa(pos1));
    crash = mystrcat(crash, ", ");
    crash = mystrcat(crash, my_itoa(pos2));
    crash = mystrcat(crash, "\n");
    write(STDOUT_FILENO, crash, mystrlen(crash));
  }
}
